package kml;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import de.micromata.opengis.kml.v_2_2_0.AltitudeMode;
import de.micromata.opengis.kml.v_2_2_0.Boundary;
import de.micromata.opengis.kml.v_2_2_0.ColorMode;
import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import de.micromata.opengis.kml.v_2_2_0.Document;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.KmlFactory;
import de.micromata.opengis.kml.v_2_2_0.LabelStyle;
import de.micromata.opengis.kml.v_2_2_0.LinearRing;
import de.micromata.opengis.kml.v_2_2_0.Placemark;
import de.micromata.opengis.kml.v_2_2_0.Polygon;
import de.micromata.opengis.kml.v_2_2_0.Style;
import editor.modelo.EditorSpace;
import editor.modelo.Floor;
import editor.modelo.JSONConverter;
import editor.modelo.ModelUtilities;
import editor.modelo.Space;
import editor.modelo.Space.Tipo;

public class KmlExporter {

	public static void main(String[] args) {
	
		new KmlExporter();
		System.out.println("fin de la operación");

	}
	private static String alpha = "DD"; 
	//aabbggrr
	private static String colorTr = alpha +"C0FFFF";	
	private static String colorOf =	alpha +"fcae8e";	
	private static String colorCl =	alpha +"aaaa88";	
	private static String colorOt =	alpha +"fcae8e";//"8eaefc00";	
	private static String colorFl =	alpha +"C0FFFF";	
			
			// SPACE_CORRIDOR_COLOR : 0xFFFFC0,
			// SPACE_FLOOR_COLOR : 0xFFFFC0,
			// SPACE_OFFICE_COLOR : 0x8eaefc,	
			// SPACE_OTHER_COLOR : 0x8eaefc,	
			// SPACE_CLASSROOM_COLOR : 0x88aaaa,
	
	private static double ang = -59*Math.PI/180;//= -55*Math.PI/180.0;
	private static double adj; // = 0*Math.PI/180;//= -55*Math.PI/180.0;
	
	//El 3digito desde atras son 3 metros aprox
	private static double latitud =  -38.701555; //-y aprox
	private static double longitud =   -62.270475; //-x aprox
	private static int scale = 1700000;
	private static double coseno;
	private static double seno;
	static{ coseno = Math.cos(ang);
			seno = Math.sin(ang);
			adj =  Math.cos(latitud*Math.PI/180);
			System.out.println(coseno*coseno + seno *seno);
			System.out.println("adj " + adj);
			}
	
	public KmlExporter(){
		File dir = ModelUtilities.getWorkingDir();
		List<Floor> pisos = ModelUtilities.loadBuilding(dir, new JSONConverter(3), false);
		
		for(int i = -1; i< 4; i++){
			createLevel(i, "nivel"+i, pisos);
		}
	}
	//toma solo los pisos con nivel = nivel;
	public void createLevel(int nivel, String name, List<Floor> pisos){
		try {
				final Kml kml = KmlFactory.createKml();
				final Document document = kml.createAndSetDocument().withName(name + ".kml").withOpen(true);
			
				document.createAndAddStyle().withId("tr")
				.createAndSetPolyStyle().withColor(colorTr);
				
				document.createAndAddStyle().withId("ot")
				.createAndSetPolyStyle().withColor(colorOt);
				
				document.createAndAddStyle().withId("au")
				.createAndSetPolyStyle().withColor(colorCl);
				
				document.createAndAddStyle().withId("of")
				.createAndSetPolyStyle().withColor(colorOf);

				for(Floor f: pisos){
					if(f.getLevel()== nivel)
					for(Space s: f.getEspacios()){
						drawSpace(s, document);
					}
				}
				kml.marshal(new File(name+".kml"));

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	}
	
	private void drawSpace(Space s, Document document){
		
		final Placemark placemark = new Placemark();
		document.getFeature().add(placemark);
		placemark.setName(s.getName());

		switch (s.getTipo()){
			case tr: placemark.setStyleUrl("#tr"); break;
			case of: placemark.setStyleUrl("#of");break;
			case au: placemark.setStyleUrl("#au");break;
			default : placemark.setStyleUrl("#ot");break;
		}
	
		final Polygon polygon = new Polygon();
		placemark.setGeometry(polygon);

		polygon.setExtrude(false);
		polygon.setTessellate(true);
		polygon.setId(s.getId());
	//	placemark.set

		polygon.setAltitudeMode(AltitudeMode.ABSOLUTE);

		final Boundary outerboundary = new Boundary();
		polygon.setOuterBoundaryIs(outerboundary);

		final LinearRing outerlinearring = new LinearRing();
		outerboundary.setLinearRing(outerlinearring);

		List<Coordinate> outercoord = new ArrayList<Coordinate>();
			outerlinearring.setCoordinates(outercoord);
			
			
		for(int i = 0; i< s.getBorde().size() +1; i++){
			Point2D p = s.getBorde().get(i%s.getBorde().size()); //vuevlvo a agregar el primero para cerrar
			//y esta negado por la diferencia de coordenadas
			double[] xy = transformXY(p.getX(), -p.getY());
			outercoord.add(new Coordinate(xy[0], xy[1], 50 + s.getHeight()/10));
			//System.out.println(x);
			//System.out.println(y);
		}

	}
	
	/*
	 * Rotacion : X: x*cos - y*sen
	 *            Y: x*sen + y*cos
	 */
	private double[] transformXY(double x, double y){
		double x_ = x*coseno - y* seno;
		x_ = x_/(scale)  + longitud;
		double y_ = x*seno + y*coseno;
		y_ = adj*y_/(scale) + (latitud);
		//ajuste aproximado por geometrica esferica
		
		System.out.println(x_ + ", " + y_);
		System.out.println(x + ", " +y);
	return new double[]{x_,  y_};
	}
}
